﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Excell_On_Services.Models;
using Excell_On_Services.ViewModels;
using System.Globalization;
using System.Web.Security;

namespace Excell_On_Services.Controllers
{
    public class CartController : Controller
    {
        //
        // GET: /Cart/

        public ViewResult Index(Cart cart, string returnUrl)
        {
            
            IQueryable<Service> list = Repository.FindAllServices();
            IDictionary<string, IEnumerable<SelectListItem>> ServiceByService = new Dictionary<string, IEnumerable<SelectListItem>>();

            foreach (var item in list )
            {
                var serviceList = new List<SelectListItem>();
                var list1 = list.Where(c => c.ParentID == item.ServiceID);
                if(list1.Count() == 0)
                    serviceList.Add(new SelectListItem { Value = item.ServiceID.ToString(), Text = item.Name });
                else
                    foreach (var itemService in list1)
                    {
                        serviceList.Add(new SelectListItem { Value = itemService.ServiceID.ToString(), Text = itemService.Name });
                    }


                if(item.ParentID == null)
                    ServiceByService.Add(item.Name, serviceList);
            }

            ViewData["Services"] = ServiceByService;
            return View(new CartIndexViewModel
            {
                Cart = cart,
                ReturnUrl = returnUrl
            });
        }

        private void DequyService(IEnumerable<Service> list,IDictionary<string, IEnumerable<SelectListItem>> serviceByService )
        {

        }
        
    

        public IEOSRepository Repository { get; set; }
        public CartController() :this (new EFEOSRepository())
        {

        }

        public CartController(IEOSRepository repository)
        {
            Repository = repository;
        }

        //public RedirectToRouteResult AddToCart(Cart cart, int serviceID, string returnUrl)
        //{
        //    Service service = Repository.FindServiceById(serviceID);
        //    cart.AddItem(service, 1, DateTime.Now, DateTime.Now);
        //    return RedirectToAction("Index", new { returnUrl });
        //}

        [HttpPost]
        public RedirectToRouteResult AddToCart(Cart cart, FormCollection collection)
        {
            try
            {
                int ServiceID = Convert.ToInt32(collection.Get("ddlServices"));
                int quantily = Convert.ToInt32(collection.Get("txtQuanlity1"));
                //DateTime startDate = Convert.ToDateTime(collection.Get("txtStartDate1"));
                DateTime startDate;
                string date = collection.Get("txtStartDate1");
                startDate = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.InvariantCulture);

                //DateTime endDate = Convert.ToDateTime(collection.Get("txtEndDate1"));
                DateTime endDate = DateTime.ParseExact(collection.Get("txtEndDate1"), "MM/dd/yyyy", CultureInfo.InvariantCulture);
                long days = (long)((TimeSpan)(endDate - startDate)).TotalDays;
                if(days <=0)
                    return RedirectToAction("Index");
                    
                Service service = Repository.FindServiceById(ServiceID);
                cart.AddItem(service, quantily, startDate, endDate);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewData["Error"] = ex.Message;
                return RedirectToAction("Index");
            }
        }


        public RedirectToRouteResult UpdateCart(Cart cart,FormCollection collection)
        {
            try
            {
                int serviceID = Convert.ToInt32(collection.Get("ServiceID"));
                int quantity = Convert.ToInt32(collection.Get("NewQuantity"));
                string date = collection.Get("NewStartDate");
                DateTime startDate = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.InvariantCulture);
                DateTime endDate = DateTime.ParseExact(collection.Get("NewEndDate"), "MM/dd/yyyy", CultureInfo.InvariantCulture);

                if (startDate < DateTime.Now)
                {
                    return RedirectToAction("Index");
                }

                long days = (long)((TimeSpan)(endDate - startDate)).TotalDays;
                if (days <= 0)
                    return RedirectToAction("Index");
                cart.UpdateItem(serviceID, quantity, startDate, endDate);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewData["Error"] = ex.Message;
                return RedirectToAction("Index");
            }
            
        }

        public RedirectToRouteResult RemoveFromCart(Cart cart, int serviceID,
        string returnUrl)
        {
            Service service = Repository.FindServiceById(serviceID);
            cart.RemoveLine(service);
            return RedirectToAction("Index", new { returnUrl });
        }

        public ViewResult Summary(Cart cart)
        {
            return View(cart);
            
        }

        public ActionResult CompleteOrder(Cart cart)
        {
            try
            {
                if(!User.Identity.IsAuthenticated)
                    return RedirectToAction("LogOnClient","Account");
                if(!User.IsInRole("Client"))
                    return RedirectToAction("LogOnClient", "Account");

                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                Repository.AddOrderByClient(cart, UserID);
                cart.Clear();
                return View();
                
            }
            catch (Exception ex)
            {
                ViewData["Error"] = ex.Message;
                return View("shared/Error");
            }
        }

        

    }
}

